package com.ruoyi.workflow.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.domain.Region;
import com.ruoyi.workflow.mapper.RegionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Service
public class RegionService {

    @Autowired
    private RegionMapper regionMapper;

    // 根据父级 ID 查询子区域
    public List<Region> getChildrenByParentId(Long parentId) {
        return regionMapper.selectChildrenByParentId(parentId);
    }

    @Transactional
    public void importRegionsFromFile(File file) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(file);
        importRegions(rootNode.get("districts"), null);
    }

    private void importRegions(JsonNode districtsNode, Long parentId) {
        if (districtsNode != null && districtsNode.isArray()) {
            for (JsonNode districtNode : districtsNode) {
                // 根据文件内容来解析字段
                Region region = parseRegion(districtNode, parentId);
                regionMapper.insertRegion(region);

                // 如果有子区域，递归地导入它们
                if (districtNode.has("districts")) {
                    importRegions(districtNode.get("districts"), region.getId());
                }
            }
        }
    }

    private Region parseRegion(JsonNode node, Long parentId) {
        Region region = new Region();
        region.setCitycode(node.get("citycode").asText(null));
        region.setAdcode(node.get("adcode").asText(null));
        region.setName(node.get("name").asText(null));
        region.setCenter(node.get("center").asText(null));
        region.setLevel(node.get("level").asText(null));
        region.setParentId(parentId);
        return region;
    }
}
